import requests
import os
import random
from datetime import datetime
from openpyxl import Workbook
import json

# 创建输出目录的函数
def create_out_directory(path='filesOutput'):
    if not os.path.exists(path):
        os.makedirs(path)
    return path

# 生成随机大小的文件并返回其路径
def generate_random_file(out_dir):
    size = random.randint(1024, 20 * 1024 * 1024)  # 1KB - 20MB
    file_name = f"file{datetime.now().strftime('%Y%m%d%H%M%S%f')}.txt"
    file_path = os.path.join(out_dir, file_name)
    with open(file_path, 'wb') as f:
        f.write(os.urandom(size))
    return file_name, size

# 将数据写入 Excel 文件
def write_to_excel(data_list, excel_path, fail_list=None):
    wb = Workbook()
    ws = wb.active
    ws.append(['文件名字', '文件大小 (Bytes)', '时间', '上传状态'])
    for data in data_list:
        ws.append(data)
    if fail_list:
        ws = wb.create_sheet(title="Failed Uploads")
        ws.append(['文件名字', '文件大小 (Bytes)', '时间', '响应码', '响应消息'])
        for fail in fail_list:
            ws.append(fail)
    wb.save(excel_path)

# 主要的发送逻辑
def send_files(base_url, headers, body_template):
    out_dir = create_out_directory()
    num_requests = random.randint(5, 30)
    total_size = 0
    data_list = []
    fail_list = []

    for _ in range(num_requests):
        file_name, file_size = generate_random_file(out_dir)
        total_size += file_size
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
        file_path = os.path.join(out_dir, file_name)
        success = False

        with open(file_path, 'rb') as f:
            # 使用文件名更新body_template中的fileName字段
            body_params = body_template.copy()
            body_params['fileName'] = file_name

            # 构建文件部分之外的其它部分，通过mime类型为None，告诉requests这是表单字段
            body_with_meta = {key: (None, value) for key, value in body_params.items()}
            # 把文件添加到multipart形式的body中
            body_with_meta['file'] = (file_name, f, 'application/octet-stream')

            response = requests.post(base_url, files=body_with_meta, headers=headers)

            print(f"响应体: {response.text}")

            if response.status_code == 200:
                success = True
            else:
                fail_list.append((file_name, file_size, timestamp, response.status_code, response.text))

            data_list.append((file_name, file_size, timestamp, '成功' if success else '失败'))

        os.remove(file_path)  # 删除文件

        if not success:
            break

    # 将数据写入到Excel文件
    excel_file_name = os.path.join(out_dir, 'upload_results.xlsx')
    write_to_excel(data_list, excel_file_name, fail_list)
    total_files_sent = len(data_list)
    return total_files_sent, total_size

# 自定义的body参数
body_params = {
    'storageType': 'OBJECT',
    'fileName': 'something',
    'fileDirectory': 'new',
    'remark': '没有bug',
    'fileUseType': 'STANDARD'
}

# 自定义HTTP请求头
headers = {
    'X-App-Id': 'IxKRtDxu',
    'X-Timestamp': '2',
    'X-Sequence-No': '2',
    'X-Signature': '2',
}

# 用于测试的URL地址（API上传接口地址）
url = 'http://10.10.2.236:32287/fileCenter/files/upload' # 替换为你的API地址

# 运行脚本
total_files, total_size = send_files(url, headers, body_params)
print(f'文件上传数量: {total_files}\n文件总量大小: {total_size} 字节')